from fastapi import APIRouter, HTTPException, Depends
from typing import List
from sqlalchemy.orm import Session
from schema import Soil_schema
from controller import Soil_controller
from database.db_init import get_db


router = APIRouter()


@router.post("/Soil", response_model=Soil_schema.Soil, tags=["Soil"])
async def create_Soil(Soil: Soil_schema.Soil, db: Session = Depends(get_db)):
    return Soil_controller.create_Soil(db, Soil)


@router.get("/Soil/{ID}", response_model=Soil_schema.Soil, tags=["Soil"])
async def get_Soil(ID: int, db: Session = Depends(get_db)):
    db_Soil = Soil_controller.get_Soil(db, ID)
    if db_Soil is None:
        raise HTTPException(status_code=404, detail="Soil not found")
    return db_Soil


@router.get("/Soil", response_model=List[Soil_schema.Soil], tags=["Soil"])
async def get_all_Soil(db: Session = Depends(get_db)):
    all_db_Soil = Soil_controller.get_all_Soil(db)
    if all_db_Soil is None:
        raise HTTPException(status_code=404, detail="0 Soil found, empty table")
    return all_db_Soil


@router.put("/Soil/{ID}", tags=["Soil"])
async def update_Soil(ID: int, field_name: str, field_value: str, db: Session = Depends(get_db)):
    try:
        db_Soil = Soil_controller.update_Soil(db, ID, field_name, field_value)
        if db_Soil is None:
            raise HTTPException(status_code=404, detail="Soil not found")
        return db_Soil
    except ValueError as error:
        raise HTTPException(status_code=400, detail=str(error))


@router.delete("/Soil/{ID}", tags=["Soil"])
async def delete_Soil(ID: int, db: Session = Depends(get_db)):
    is_deleted = Soil_controller.delete_Soil(db, ID)
    if is_deleted is None:
        raise HTTPException(status_code=404, detail=f'Sample {ID} does not exist in database')
    else:
        return {'message': f'Successfully delete sample {ID}'}
